import UIKit

class TF_AnnounceRollView: UIView {
    /** 代理对象 */
    @objc public weak var delegate : TF_AnnounceRollViewDelegate?
    @objc public let content = UILabel()
    @objc public var url:NSString = ""
    let view = UIView()
    let image = UIImageView()
    let Xbtn = UIButton()
    var isHiddeView:Bool = false
    var duration:NSInteger = 0
    var timer:Timer!
    var basicAni:CABasicAnimation?
    @objc public func timerStop()
    {
        if((self.timer) != nil)
        {
            self.timer!.invalidate()
            self.timer = nil
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isHidden = true
        
        self.addSubview(self.image)
        self.image.image = UIImage.init(named: "HTLive.bundle/liveingtongzhi")
 
        self.image.contentMode = .scaleAspectFit;
        
        self.backgroundColor = UIColor(red: 255/255.0, green: 240/255.0, blue: 212/255.0, alpha: 1.0)
    
        self.addSubview(self.Xbtn)
        self.Xbtn.setImage(UIImage.init(named: "HTLive.bundle/closetongzhi"), for: .normal)
        self.Xbtn.addTarget(self, action: #selector(self.closeWinnersCLick), for: UIControl.Event.touchUpInside)

        self.view.clipsToBounds = true;
        self.addSubview(self.view)
        
        self.view.addSubview(self.content)
        self.content.font = UIFont.PingFang(size: 16)
     
        self.content.textColor = UIColor(red: 112/255.0, green: 53/255.0, blue: 7/255.0, alpha: 1.0)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let imageW:CGFloat = 46
        let imageH:CGFloat = 31
        let imageX:CGFloat = 9
        let imageY:CGFloat = 0
        self.image.frame = CGRect(x: imageX, y: imageY, width: imageW, height: imageH)
       
        
        let XbtnW:CGFloat = self.frame.size.height
        self.Xbtn.frame = CGRect(x: self.frame.size.width - XbtnW, y: 0, width: XbtnW, height: XbtnW)
    
        let contentWidth:CGFloat = self.frame.size.width - self.image.frame.maxX - self.Xbtn.frame.size.width
        self.view.frame = CGRect(x: self.image.frame.maxX, y: 0, width: contentWidth, height: self.frame.size.height)
        
    }
    @objc func closeWinnersCLick()
    {
        DispatchQueue.main.async {
            
            self.isHiddeView = true
            self.isHidden = true
            self.timerStop()
          
            if self.delegate != nil && (self.delegate?.responds(to: #selector(TF_AnnounceRollViewDelegate.onCloseWinnersCLick) )   )!{
                
                self.delegate?.onCloseWinnersCLick()
                
            }

            
           }
    }
    @objc func timer_Action()
    {
        self.duration = self.duration - 1
        if (self.duration <= 0 ) {
            self.closeWinnersCLick()
        
        }
    }
    @objc public func initUI(content:NSString,link:NSString,duration:NSInteger)
    {

        self.isHidden = false
        
       self.isHiddeView = false

        self.url = link

        self.duration = 0;
        self.content.layer.removeAllAnimations()
        self.timerStop()
       
        if (self.duration != 0) {
            
            if((self.timer) == nil)
            {
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timer_Action), userInfo: nil, repeats: true)
                RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
                self.timer.fire()
            }
            
        }
        self.content.text = content as String
        self.content.textAlignment = .left
        let attrsSize: CGSize = content.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 16)])
        
        var viewWidth:CGFloat = attrsSize.width

        let contentWidth:CGFloat = self.frame.size.width - self.image.frame.maxX - self.Xbtn.frame.size.width
        var contentX = contentWidth
        if (viewWidth < contentWidth) {
            contentX = 0
            viewWidth = contentWidth
        }
        self.content.frame = CGRect(x: contentX, y: 0, width: viewWidth, height: self.bounds.size.height)

        //TFAutoScrollLabel
        if self.content.frame.width > contentWidth {
            self.start_Animation()
        }

    }

    func start_Animation()
    {
        
//    let movePath = UIBezierPath()
//
//    movePath.move(to: CGPoint(x: self.view.frame.width, y: self.content.bounds.size.height/2))
//
//    movePath.addLine(to: CGPoint(x: -self.content.frame.size.width+10, y: self.content.bounds.size.height/2))
//
//    let moveAnimation = CAKeyframeAnimation.init(keyPath: "position")
//
//    moveAnimation.path = movePath.cgPath
//    moveAnimation.isRemovedOnCompletion = false
//
//    moveAnimation.fillMode = kCAFillModeForwards
//
//    let interval:CGFloat = self.content.frame.size.width / 35
//
//    moveAnimation.duration = interval
//
//    moveAnimation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
//
//    self.content.layer.add(moveAnimation, forKey: "animationViewPosition")
        
        if self.basicAni != nil {
            self.basicAni = nil
        }
     
        //创建动画对象
        let basicAni = CABasicAnimation()
        self.basicAni = basicAni
        //设置动画属性
        basicAni.keyPath = "position";

        //设置动画的起始位置。也就是动画从哪里到哪里
        basicAni.fromValue = NSValue.init(cgPoint: CGPoint(x: self.content.frame.size.width/2+self.view.frame.size.width, y: self.content.frame.size.height/2))

        //动画结束后，layer所在的位置
        basicAni.toValue = NSValue.init(cgPoint: CGPoint(x:-(self.content.frame.size.width/2), y: self.content.frame.size.height/2))
        
     
        //动画持续时间
        basicAni.duration = self.content.frame.size.width/35

        //动画填充模式
        basicAni.fillMode = CAMediaTimingFillMode.forwards

        //动画完成不删除
        basicAni.isRemovedOnCompletion = false


        basicAni.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
        //把动画添加到要作用的Layer上面

        self.content.layer.add(basicAni, forKey: "animationViewPosition")
//        [self.content.layer addAnimation:basicAni forKey:nil];
        

    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
 
        // 重点开始！！UITouch 获取在 barrageView 坐标系下的坐标
        for touch : AnyObject in touches {
            
       let t : UITouch = touch as! UITouch;
            
        let  touchPoint =  t.location(in: self.view)
      
            if ((self.content.layer.presentation()?.hitTest(touchPoint)) != nil) {
                
                if self.delegate != nil && (self.delegate?.responds(to: #selector(TF_AnnounceRollViewDelegate.marqueeClick) )   )!{
                    
                    self.delegate?.marqueeClick()
                    
                }
                return;
            }
 
        }

    }
    
}

@objc public protocol TF_AnnounceRollViewDelegate : NSObjectProtocol {
    //打开链接
    func marqueeClick()
    //关闭通知
    func onCloseWinnersCLick()

}
